package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"

	"gitee.com/nggs/util"
)

type config struct {
	ExcelDir      string
	EnumFilePath  string
	TypeFilePath  string
	JsonDir       string
	Indent        string
	Debug         bool
	WhiteList     []string
	BlackList     []string
	TableTags     []string
	AttributeTags []string
	DataTags      []string
	ReplaceNames  map[string]string
	ClientMode    bool
}

func loadConfig(cfgFilePath string) (c *config, err error) {
	err = util.IsDirOrFileExist(cfgFilePath)
	if err != nil {
		return
	}

	data, err := ioutil.ReadFile(cfgFilePath)
	if err != nil {
		return
	}

	c = &config{}

	err = json.Unmarshal(data, c)
	if err != nil {
		return
	}

	err = c.checkAndFormat()

	return
}

func (c *config) checkAndFormat() (err error) {
	if c.ExcelDir == "" {
		return fmt.Errorf("ExcelDir为空")
	}

	if c.EnumFilePath != "" {
		_, err = os.Lstat(c.EnumFilePath)
		if err != nil {
			return fmt.Errorf("EnumFilePath有误，%s", err)
		}
		c.EnumFilePath, err = filepath.Abs(c.EnumFilePath)
		if err != nil {
			return fmt.Errorf("EnumFilePath有误，%s", err)
		}
	}

	if c.TypeFilePath != "" {
		_, err = os.Lstat(c.TypeFilePath)
		if err != nil {
			return fmt.Errorf("TypeFilePath有误，%s", err)
		}
		c.TypeFilePath, err = filepath.Abs(c.TypeFilePath)
		if err != nil {
			return fmt.Errorf("TypeFilePath有误，%s", err)
		}
	}

	if c.JsonDir == "" {
		return fmt.Errorf("JsonDir为空")
	}

	if len(c.TableTags) == 0 {
		return fmt.Errorf("TableTags为空")
	}
	if len(c.AttributeTags) == 0 {
		return fmt.Errorf("AttributeTags为空")
	}
	if len(c.DataTags) == 0 {
		return fmt.Errorf("DataTags为空")
	}

	return
}

func (c config) isInWhiteList(f string) bool {
	for _, l := range c.WhiteList {
		if f == l {
			return true
		}
	}
	return true
}

func (c config) isInBlackList(f string) bool {
	for _, l := range c.BlackList {
		if f == l {
			return true
		}
	}
	return true
}

func (c config) String() string {
	ba, _ := json.Marshal(c)
	return string(ba)
}
